package handConsistentHash;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author 03010570
 * @date 2020/07/08
 * describe:    哈希算法
 */
public class HashFunction {

    private MessageDigest instance;

    public  HashFunction()  {
        try {
            instance=MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }

    /**
     *  根据名称 获取 哈希值
     * @param name
     * @return
     */
    public Long hash2(String name) {
        System.out.println(Integer.valueOf(name.hashCode()).longValue());
        return Integer.valueOf(name.hashCode()).longValue();
    }

    public Long hash(String key){
        instance.reset();
        instance.update(key.getBytes());
        byte[] digest = instance.digest();
        long res= 0;
        for(int i= 0 ;i<4;i++){
            res <<=8;
            res |= digest[i] & 0xFF;
        }
//        System.out.println(res);
        return res;
    }
}
